package com.example.mychat

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.example.mychat.network.ChatManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import android.util.Log
import android.content.Context
import com.airbnb.lottie.LottieAnimationView
import kotlinx.coroutines.withContext
import com.example.mychat.view.LoadingButton
import kotlinx.coroutines.delay

class LoginActivity : AppCompatActivity() {
    private lateinit var usernameInput: EditText
    private lateinit var passwordInput: EditText
    private lateinit var serverIpInput: EditText
    private lateinit var loginButton: LoadingButton

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        initViews()
        loadSavedCredentials()

        val lottieAnimationView = findViewById<LottieAnimationView>(R.id.lottieAnimationView)
        lottieAnimationView.setAnimation(R.raw.anime)
        lottieAnimationView.playAnimation()
    }

    private fun initViews() {
        usernameInput = findViewById(R.id.usernameInput)
        passwordInput = findViewById(R.id.passwordInput)
        serverIpInput = findViewById(R.id.serverIpInput)
        loginButton = findViewById(R.id.loginButton)

        loginButton.setOnClickListener {
            login()
        }
    }

    private fun loadSavedCredentials() {
        val sharedPrefs = getSharedPreferences("ChatPrefs", Context.MODE_PRIVATE)
        val savedUsername = sharedPrefs.getString("username", "")
        val savedPassword = sharedPrefs.getString("password", "")
        val savedServerIp = sharedPrefs.getString("serverIp", "10.129.16.118")
        
        if (!savedUsername.isNullOrEmpty() && !savedPassword.isNullOrEmpty()) {
            usernameInput.setText(savedUsername)
            passwordInput.setText(savedPassword)
        }
        serverIpInput.setText(savedServerIp)
    }

    private fun saveCredentials(username: String, password: String, serverIp: String) {
        val sharedPrefs = getSharedPreferences("ChatPrefs", Context.MODE_PRIVATE)
        sharedPrefs.edit().apply {
            putString("username", username)
            putString("password", password)
            putString("serverIp", serverIp)
            apply()
        }
    }

    private fun login() {
        val username = usernameInput.text.toString().trim()
        val password = passwordInput.text.toString().trim()
        val serverIp = serverIpInput.text.toString().trim()

        if (username.isEmpty() || password.isEmpty() || serverIp.isEmpty()) {
            Toast.makeText(this, "请填写所有字段", Toast.LENGTH_SHORT).show()
            return
        }

        Log.d("LoginActivity", "开始登录流程: username=$username, serverIp=$serverIp")
        loginButton.startLoading()
        Toast.makeText(this, "正在连接服务器...", Toast.LENGTH_SHORT).show()

        lifecycleScope.launch {
            try {
                val chatClient = ChatManager.createClient(
                    serverAddress = serverIp,
                    messageCallback = { message ->
                        Log.d("LoginActivity", "收到服务器响应: $message")
                        runOnUiThread {
                            handleLoginResponse(message, username, password, serverIp)
                        }
                    },
                    onConnectionError = {
                        Log.e("LoginActivity", "连接错误")
                        runOnUiThread {
                            Toast.makeText(this@LoginActivity, "连接服务器失败", Toast.LENGTH_SHORT).show()
                            loginButton.reset()
                        }
                    }
                )

                Log.d("LoginActivity", "尝试连接服务器")
                val connected = withContext(Dispatchers.IO) {
                    chatClient.connect(
                        successCallBack = {
                            try {
                                Log.d("LoginActivity", "连接成功，准备发送登录请求")
                                val loginMessage = "LOGIN:$username:$password"
                                lifecycleScope.launch {
                                    try {
                                        chatClient.sendMessage(loginMessage)
                                        Log.d("LoginActivity", "登录请求已发送")
                                    } catch (e: Exception) {
                                        Log.e("LoginActivity", "发送登录请求失败", e)
                                        withContext(Dispatchers.Main) {
                                            Toast.makeText(this@LoginActivity, "发送登录请求失败", Toast.LENGTH_SHORT).show()
                                            loginButton.reset()
                                        }
                                        chatClient.disconnect()
                                    }
                                }
                            } catch (e: Exception) {
                                Log.e("LoginActivity", "登录过程出错", e)
                                runOnUiThread {
                                    loginButton.reset()
                                    Toast.makeText(this@LoginActivity, "连接出错: ${e.message}", Toast.LENGTH_SHORT).show()
                                }
                            }
                        },
                        failureCallback = {
                            Log.e("LoginActivity", "连接服务器失败")
                            runOnUiThread {
                                loginButton.reset()
                                Toast.makeText(this@LoginActivity, "连接服务器失败", Toast.LENGTH_SHORT).show()
                            }
                        }
                    )
                }
            } catch (e: Exception) {
                Log.e("LoginActivity", "登录过程出错", e)
                runOnUiThread {
                    loginButton.reset()
                    Toast.makeText(this@LoginActivity, "连接出错: ${e.message}", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun handleLoginResponse(response: String, username: String, password: String, serverIp: String) {
        Log.d("LoginActivity", "处理登录响应: $response")
        when {
            response.startsWith("LOGIN_SUCCESS:") -> {
                loginButton.showSuccess()
                lifecycleScope.launch {
                    delay(1000) // 显示成功图标1秒
                    saveCredentials(username, password, serverIp)
                    startChat(username)
                }
            }
            response == "LOGIN_FAILED" -> {
                loginButton.reset()
                Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT).show()
                loginButton.reset()
                ChatManager.getCurrentClient()?.disconnect()
            }
            else -> {
                Log.d("LoginActivity", "收到未知响应: $response")
//                Toast.makeText(this, "未知响应: $response", Toast.LENGTH_SHORT).show()
                loginButton.reset()
            }
        }
    }

    private fun startChat(username: String) {
        Log.d("LoginActivity", "开始跳转到聊天界面")
        val intent = Intent(this, MainActivity::class.java).apply {
            putExtra("username", username)
        }
        startActivity(intent)
        finish()
    }
} 